﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;


/// <summary>
/// 这个扩展类主要是因为unity的linq的GC问题无法使用GC，但是有需要部分功能时，重新造的轮子
/// 以及其他额外可能遇到的查询
/// </summary>
public static class MyQueryExtension {

    public delegate U Selector<T, U>(T o);
    public delegate U Adder<U>(U l, U r);

    public static T MQ_Max<T>(this IEnumerable<T> h, System.Comparison<T> cmp) 
    {
        
        T max = default(T);
        bool changed = false; ;
        foreach(var t in h)
        {
            if (!changed || cmp(t, max) >= 0)
            {
                changed = true;
                max = t;
            }
        }
        if (changed || max == null) return max;
        else throw (new System.Exception("枚举数为空，且结果类型不可空"));
    }

    public static T MQ_Min<T>(this IEnumerable<T> h, System.Comparison<T> cmp) 
    {
        T min = default(T);
        bool changed = false;
        foreach (var t in h)
        {
            if (!changed || cmp(t, min) >= 0)
            {
                changed = true;
                min = t;
            }
        }
        if (changed || min == null) return min;
        else throw (new System.Exception("枚举数为空，且结果类型不可空"));
    }

    

    public static U MQ_Sum<T,U>(this IEnumerable<T> h, Selector<T,U> selector ,Adder<U> adder)
    {
        
        U sum = default(U);
        bool summed = false;
        foreach(var t in h)
        {
            if (!summed) summed = true;
            sum = adder(sum, selector(t));
        }
        if (summed || sum == null) return sum;
        else throw (new System.Exception("枚举数为空，且结果类型不可空"));
    }


}
